﻿using QBZ.Evaluation.Models;
using QBZ.Evaluation.Repositories.DataAccess;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace QBZ.Evaluation.Repositories
{
    public class RoleRepository
    {
        private dbEvaluationContext _db;
        public RoleRepository(dbEvaluationContext db)
        {
            _db = db;
        }

        public List<RoleModel> GetAll()
        {
            var roleChilds =
                (from rc in _db.TbRoleChild
                 where rc.RoleChildIsDelete == false
                 orderby rc.RoleId
                 select new RoleChildModel
                 {
                     RoleId = rc.RoleId,
                     RoleChildId = rc.RoleChildId,
                     RoleChildName = rc.RoleChildName,
                     RoleChildDescription = rc.RoleChildDescription,
                     RoleChildLevel = rc.RoleChildLevel
                 }).ToList();

            var roleIds = roleChilds.Select(rc => rc.RoleId).Distinct().ToList();

            var roles =
                (from r in _db.TbRole
                 where r.RoleIsDelete == false && roleIds.Contains(r.RoleId)
                 select new RoleModel
                 {
                     RoleId = r.RoleId,
                     RoleName = r.RoleName,
                     RoleDescription = r.RoleDescription,
                 }).ToList();

            foreach(var role in roles)
            {
                role.roleChilds = (from rch in roleChilds where rch.RoleId == role.RoleId select rch).ToList();
            }
            //roles[0].RoleDescription = Guid.NewGuid().ToString();
            return roles;
        }
    }
}
